package org.tony.spider.common;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;

import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
 * A web browser simulator
 * @author tony
 */
public class Browser
{
  private HttpClient core;
  private String     userAgent;
  private Charset    charset;

  public Browser()
  {
    initialBasicConfig();
    core = new DefaultHttpClient();
  }

  private void initialBasicConfig()
  {
    charset = Charset.forName("UTF-8");
    userAgent = "Mozilla/5.0";
  }

  private String get(Address address)
  {
    String url = address.buildUrl();
    HttpGet get = new HttpGet(url);
    try
    {
      HttpResponse response = core.execute(get);
      Header contentEncoding = response.getEntity().getContentEncoding();
      System.out.println(Arrays.toString(response.getAllHeaders()));
      if (contentEncoding != null)
      {
        System.out.println(contentEncoding);
        return EntityUtils.toString(response.getEntity(), contentEncoding.getValue());
      }
      return EntityUtils.toString(response.getEntity(), charset);
    }
    catch (ClientProtocolException e)
    {
      // catch exception 
    }
    catch (IOException e)
    {
      //catch exception
    }
    finally
    {
      get.releaseConnection();
    }
    return null;
  }

  private String post(Address address)
  {
    return null;
  }

  public String open(Address address)
  {
    System.out.println("open(" + address.getUrl() + ")");
    switch (address.getRequestType())
    {
      case post:
        return post(address);
      case get:
      default:
        return get(address);
    }
  }

  public void setProxy(String host, Integer port)
  {
    core.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(host, port));
  }

  public String getUserAgent()
  {
    return userAgent;
  }

  public void setUserAgent(String userAgent)
  {
    this.userAgent = userAgent;
  }

  public Charset getCharset()
  {
    return charset;
  }

  public void setCharset(Charset charset)
  {
    this.charset = charset;
  }

  public void shutdown()
  {
  }

  public static enum RequestType {
    get, post
  }
}
